#include <53func.h>
typedef struct shareRes_s {
    int num; // 饭的数量
    pthread_mutex_t mutex;
    pthread_cond_t cond;
} shareRes_t;

void * threadFunc(void *arg){
    shareRes_t * pShareRes = (shareRes_t *)arg;
    pthread_mutex_lock(&pShareRes->mutex);
    while(pShareRes->num == 0){ // 把if改成while可以避免虚假唤醒
        pthread_cond_wait(&pShareRes->cond,&pShareRes->mutex);
    }
    --pShareRes->num;
    printf("I got food! remain = %d\n",pShareRes->num);
    pthread_mutex_unlock(&pShareRes->mutex);
    pthread_exit(NULL);
}
int main(int argc, char *argv[])
{
    shareRes_t shareRes;
    shareRes.num = 0;
    pthread_mutex_init(&shareRes.mutex,NULL);
    pthread_cond_init(&shareRes.cond,NULL);
    
    pthread_t tid1, tid2;
    pthread_create(&tid1,NULL,threadFunc,&shareRes);
    pthread_create(&tid2,NULL,threadFunc,&shareRes);

    sleep(1);
    printf("Add 1 food!\n");
    pthread_mutex_lock(&shareRes.mutex);
    ++shareRes.num;
    pthread_cond_broadcast(&shareRes.cond);
    pthread_mutex_unlock(&shareRes.mutex);

    pthread_join(tid1,NULL);
    pthread_join(tid2,NULL);
    return 0;
}

